package com.changgou.mq;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * @author ：hushengjin
 */

@Configuration
public class RabbitMqConfig {

    @Autowired
    private Environment env;

    /**
     * 创建队列
     *
     * @return
     */
    @Bean
    public Queue orderQueue() {
        return new Queue(env.getProperty("mq.pay.queue.order"),true);
    }

    /**
     * 到期数据队列
     * @return
     */
    @Bean
    public Queue seckillOrderTimerQueue() {
        return new Queue(env.getProperty("mq.pay.queue.seckillordertimer"), true);
    }

    /**
     * 超时数据队列
     *
     * @return
     */
    @Bean
    public Queue delaySeckillOrderTimerQueue() {
        return QueueBuilder.durable(env.getProperty("mq.pay.queue.seckillordertimerdelay"))
                //消息超时进入死信队列,绑定死信队列交换机
                .withArgument("x-dead-letter-exchange", env.getProperty("mq.pay.exchange.order"))
                //按照路由规则发送给指定的队列(绑定指定的routing-key 因为这里的queue和routing-key相同)
                .withArgument("x-dead-letter-routing-key", env.getProperty("mq.pay.queue.seckillordertimer"))
                .build();
    }

    /**
     * 创建交换机
     *
     * @return
     */
    @Bean
    public Exchange orderExchange() {
        return new DirectExchange(env.getProperty("mq.pay.exchange.order"), true, false);
    }

    /**
     * 交换机绑定队列
     *
     * @return
     */
    @Bean
    public Binding orderQueueBinding(Queue orderQueue, Exchange orderExchange) {
        return BindingBuilder.bind(orderQueue).to(orderExchange).with(env.getProperty("mq.pay.routing.key")).noargs();
    }

    /**
     * 交换机绑定队列
     *
     * @param seckillOrderTimerQueue
     * @param orderExchange
     * @return
     */
    public Binding basicBinding(Queue seckillOrderTimerQueue, Exchange orderExchange) {
        return BindingBuilder.bind(seckillOrderTimerQueue).to(orderExchange).with(env.getProperty("mq.pay.queue.seckillordertimer")).noargs();
    }

}
